﻿using System;
using Newtonsoft.Json.Serialization;

namespace TypeScriptJson.Generator
{
	public class DictionaryTypeMapping: TypeMapping
	{
		public JsonDictionaryContract Contract { get; private set; }
		public TypeMapping KeyTypeMapping { get; set; }
		public TypeMapping ValueTypeMapping { get; set; }

		public override bool IsGenerateDeclaration
		{
			get { return false; }
		}

		public override string GetTypeNameInternal()
		{
			var keyTypeName = KeyTypeMapping.TypeName;
			if (keyTypeName != "number" && keyTypeName != "any")
				keyTypeName = "string";
			return "Dictionary$" + keyTypeName + "$" + ValueTypeMapping.TypeName;
		}

		public override void WriteTypeDeclaration(TypeScriptCodeWriter codeWriter, GeneratorContext context)
		{
			throw new InvalidOperationException();
		}

		public override void WriteTypeReference(TypeScriptCodeWriter codeWriter, string currentModule)
		{
			if (CustomTypeName != null)
				base.WriteTypeReference(codeWriter, currentModule);
			else
			{
				codeWriter.WriteStartBlock(isAtStartOfLine: false, isEndOfLine: false, indent: false);
				codeWriter.Writer.Write(" [key: ");
				var keyTypeName = KeyTypeMapping.TypeName;
				if (keyTypeName != "number" && keyTypeName != "any")
					keyTypeName = "string";
				codeWriter.Writer.Write(keyTypeName);
				codeWriter.Writer.Write("]: ");
				ValueTypeMapping.WriteTypeReference(codeWriter, currentModule);
				codeWriter.Writer.Write("; ");
				codeWriter.WriteEndBlock(isAtStartOfLine: false, isEndOfLine: false, unindent: false);
			}
		}

		public DictionaryTypeMapping(JsonDictionaryContract contract) : base(contract.UnderlyingType)
		{
			Contract = contract;
		}

		protected override void ProcessInternal(GeneratorContext context)
		{
			KeyTypeMapping = context.MapType(Contract.DictionaryKeyType);
			ValueTypeMapping = context.MapType(Contract.DictionaryValueType);
		}
	}
}
